import { lazy } from 'react'
import { RouteObject, createHashRouter } from 'react-router-dom'
import { MenuItemType } from 'antd/es/menu/interface'
// import App from '../App'

const App = lazy(() => import('@/App'))
const NotFound = lazy(() => import('@/components/404'))

export type AdminRouterItem = RouteObject & {
  // set antd menu props in meta
  meta?: MenuItemType
  children?: AdminRouterItem[]
  hidden?: boolean
}

/**
 * auto load route from views/***\/*.router.ts
 * @returns route
 */
const loadRouteModules = async () => {
  const routeModuleFiles = import.meta.glob('../views/**/*.router.tsx', {
    eager: true,
    import: 'default',
  })
  const routeModules: AdminRouterItem[] = []

  for await (const [key, module] of Object.entries(routeModuleFiles)) {
    console.log('key = ', key, 'module = ', module)

    if (module) {
      const routes = Array.isArray(module) ? module : [module]
      routeModules.push(...routes)
    }
  }

  return routeModules
}

export const routes: AdminRouterItem[] = [...(await loadRouteModules())]

const router = createHashRouter([
  {
    path: '/',
    element: <App />,
    children: routes,
  },
  {
    path: '*',
    element: <NotFound />,
  },
])

export default router
